<template>
  <div id="shopcart">
    <top-header title="购物车" :isRoute="isRoute" />
    <div class="empty-shopcart" v-if="shopcartList.length <= 0">您的购物车空空如也！快去加车</div>
    <div class="shopcart-list">
      <div class="shopcart-item" v-for="item in shopcartList" :key="item.goodsId">
        <div class="goods-img">
          <img :src="item.img_url" />
        </div>
        <div class="info">
          <p>{{item.title | strLimit(20)}}</p>
          <p>售价：{{item.sell_price}}</p>
          <div class="edit-shopcart">
            <button @click="jianQuantity(item.goodsId)">-</button>
            <input type="number" :value="item.quantity" disabled ref="goodsQuantity" />
            <button @click="addQuantity(item.goodsId)">+</button>
          </div>
        </div>
      </div>
      <div style="text-align:right;" v-if="shopcartList.length > 0">总计：&yen;{{getTotalAmount}}</div>
    </div>
  </div>
</template>
<script>
import "./index.less";
import { userData, shopcartData, middleVue } from "../../services";
import { each, map, find, findIndex } from "lodash";
export default {
  data() {
    return {
      isRoute: true,
      shopcartList: []
    };
  },
  methods: {
    async jianQuantity(goodsId) {
      let resultQuantity = 0;
      if (userData.getUserData()) {
        // 在线购物车的业务处理
        const currentGoods = find(
          this.shopcartList,
          item => item.goodsId === goodsId
        );
        if (currentGoods.quantity > 1) {
          const setShopcartResponse = await this.$axios.post("add_shopcart", {
            user_name: userData.getUserData(),
            goodsId,
            quantity: -1
          });
          console.log(setShopcartResponse.data.msg);
          const shopcartListResponse = await this.$axios.get(
            "getshopcarts?account=" + userData.getUserData()
          );
          this.shopcartList = shopcartListResponse.data.message;
        }
      } else {
        map(this.shopcartList, (item, index) => {
          if (item.goodsId === goodsId) {
            if (item.quantity > 1) {
          //  需要把对象里的值保存给一个变量先存起来，然后再赋值，不然拿不到
              let currentQuantity = item.quantity;
              currentQuantity--;
              this.$refs.goodsQuantity[index].value = currentQuantity;
              // 更新购物车localStorage里的数据
              shopcartData.setShopcartData({
                goodsId: item.goodsId,
                quantity: -1,
                stockQuantity: item.stockQuantity,
                title: item.title,
                sell_price: item.sell_price,
                img_url: item.img_url
              });
            }
          }
          return item;
        });
        // 根据上边更新后的数据重新给shopcartList赋值，强制触发computed模块里的计算方法
        this.shopcartList = shopcartData.getShopcartData();
      }
      // 通过$emit通知Tabbar里的总数量的更新
      each(this.shopcartList, item => {
        resultQuantity += item.quantity;
      });
      middleVue.$emit("getTotalQuantity", resultQuantity);
    },
    async addQuantity(goodsId) {
      let resultQuantity = 0;
      if (userData.getUserData()) {
        // 在线购物车的业务处理
        const currentGoods = find(
          this.shopcartList,
          item => item.goodsId === goodsId
        );
        if (currentGoods.quantity < currentGoods.stock_quantity) {
          const setShopcartResponse = await this.$axios.post("add_shopcart", {
            user_name: userData.getUserData(),
            goodsId,
            quantity: 1
          });
          console.log(setShopcartResponse.data.msg);
          const shopcartListResponse = await this.$axios.get(
            "getshopcarts?account=" + userData.getUserData()
          );
          this.shopcartList = shopcartListResponse.data.message;
        }
      } else {
        // 从localStorage下手
        const currentGoods = find(
          this.shopcartList,
          item => item.goodsId === goodsId
        );
        if (currentGoods.quantity < currentGoods.stockQuantity) {
          shopcartData.setShopcartData({
            goodsId: currentGoods.goodsId,
            quantity: 1,
            stockQuantity: currentGoods.stockQuantity,
            title: currentGoods.title,
            sell_price: currentGoods.sell_price,
            img_url: currentGoods.img_url
          });
          // 更新完localStorage后，从localStorage里的值来更新number框里的值
          each(shopcartData.getShopcartData(), (item, index) => {
            if (item.goodsId === goodsId) {
              this.$refs.goodsQuantity[index].value = item.quantity;
            }
          });
          // 重新更新Model里的shopcartList，来触发computed
          this.shopcartList = shopcartData.getShopcartData();
        }
      }
      // 通过$emit通知Tabbar里的总数量的更新
      each(this.shopcartList, item => {
        resultQuantity += item.quantity;
      });
      middleVue.$emit("getTotalQuantity", resultQuantity);
    }
  },
  computed: {
    getTotalAmount() {
      let totalAmount = 0;
      if (userData.getUserData()) {
        each(this.shopcartList, item => {
          totalAmount += item.quantity * item.sell_price;
        });
      } else {
        this.shopcartList = shopcartData.getShopcartData() || [];
        each(this.shopcartList, item => {
          totalAmount += item.quantity * item.sell_price;
        });
      }
      return totalAmount;
    }
  },
  async created() {
    if (userData.getUserData()) {
      const response = await this.$axios.get("getshopcarts", {
        params: {
          account: userData.getUserData()
        }
      });
      this.shopcartList = response.data.message;
    } else {
      // 用户未登录则从localStorage里调取数据
      this.shopcartList = shopcartData.getShopcartData() || [];
    }
  },
  mounted() {
    // 开启一个自定义事件，监听登录成功后获取用户的在线购物车列表数据
    middleVue.$on("getShopcartList", shopcartList => {
      this.shopcartList = shopcartList;
    });
  },
  destroyed() {
    middleVue.$off("getShopcartList");
  }
};
</script>
